package com.chaosj.skill.zipkin.annotations

import com.chaosj.skill.zipkin.context.ApplicationContext
import com.google.common.base.Strings
import com.google.common.collect.Lists

/**
 * @Description:
 * @author: caoyangjie
 * @date: 2019年12月2019/12/6日 09:07
 * @Copyright: © 赢时胜
 */
class DelegateSpanParser implements ISpanParser{
    List<ISpanParser> parsers

    public ISpanParser setParsers(ISpanParser... parsers) {
        this.parsers = Optional.ofNullable(this.parsers).orElse(Lists.newArrayList())
        this.parsers.addAll(Arrays.asList(parsers))
        return this
    }

    @Override
    String parserAnnotate(NewSpan yssSpan, Object[] args) {
        String annotate = null
        for ( ISpanParser parser:parsers ) {
            if( !parser.filter(yssSpan,args) ){
                continue
            }
            if(!Strings.isNullOrEmpty(annotate=parser.parserAnnotate(yssSpan,args))){
                break
            }
        }
        return !Strings.isNullOrEmpty(annotate)? annotate : null
    }

    @Override
    String parserName(NewSpan yssSpan, Object[] args) {
        String name = null
        for ( ISpanParser parser:parsers ) {
            if( !parser.filter(yssSpan,args) ){
                continue
            }
            if(!Strings.isNullOrEmpty(name = parser.parserName(yssSpan,args)) ){
                break
            }
        }
        return !Strings.isNullOrEmpty(name)? name : ApplicationContext.getBean(ApplicationContext.Builder.class).getLocalServiceName()
    }

    @Override
    void parserTag(NewSpan yssSpan, Object[] args, brave.Span span) {
        for ( ISpanParser parser:parsers ) {
            if( !parser.filter(yssSpan,args) ){
                continue
            }
            parser.parserTag(yssSpan, args, span)
        }
    }

    @Override
    boolean filter(NewSpan yssSpan, Object[] args) {
        true
    }
}
